<style scoped lang="scss">
.meeting-room-container {
  display: flex;
  /* 减去页面头部高度 */
  height: calc(100vh - 120px);

}

/* 左侧会议室列表 */
.room-list-sidebar {
  width: 280px;
  background-color: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  height: 100%;
  flex-shrink: 0;
}

.room-list-header {
  border-bottom: 1px solid #e4e7ed;
  background-color: #fafafa;
}

.room-list-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.room-list {
  flex: 1;
  overflow-y: auto;
}

.room-item {
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid #ddd;
  height: 65px;

  ;
}

.room-item:hover {
  background-color: #f0f9ff;
}

.room-item.active {
  background-color: #409EFF;
  color: white;
}

.room-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.room-info {
  font-size: 12px;
  opacity: 0.8;
}

/* 右侧时间表格区域 */
.schedule-area {
  display: flex;
  flex-direction: column;
  min-width: 0;
  /* 防止flex子项溢出 */
}

.time-header {
  display: flex;
  border-bottom: 2px solid #e4e7ed;
}

.time-cell {
  flex: 1;
  padding: 15px 5px;
  text-align: center;
  font-weight: 500;
  color: #606266;
  border-right: 1px solid #e4e7ed;
  min-width: 60px;
  background-color: #fafafa;
}

.time-table {
  flex: 1;
  position: relative;
  overflow-x: auto;
}

.room-row {
  display: flex;
  height: 65px;
  border-bottom: 1px solid #ddd;
}

.time-slot {
  flex: 1;
  border-right: 1px solid #e4e7ed;
  position: relative;
  cursor: pointer;
  min-width: 30px;
  transition: background-color 0.2s;
}

.past-time-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(128, 128, 128, 0.2);
  pointer-events: none;
  z-index: 10;
}

.time-slot:hover {
  background-color: #f0f9ff;
}

/* 鼠标跟随蓝线 */
.mouse-line {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 2px;
  background-color: #409EFF;
  pointer-events: none;
  z-index: 10;
}

/* 选择区域高亮 */
.selection-highlight {
  position: absolute;
  background-color: rgba(64, 158, 255, 0.3);
  border: 2px solid #409EFF;
  pointer-events: none;
  z-index: 5;
}

/* 事件块 */
.event-block {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 80%;
  display: flex;
  align-items: center;
  z-index: 3;
  padding:10px;
}

/* 预约确认弹窗 */
.booking-confirm h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.booking-confirm p {
  margin: 5px 0;
  color: #606266;
}

.booking-actions {
  margin-top: 15px;
  text-align: right;
}

.booking-actions .el-button {
  margin-left: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .room-list-sidebar {
    width: 200px;
  }

  .time-cell {
    min-width: 40px;
    padding: 10px 2px;
    font-size: 12px;
  }

  .time-slot {
    min-width: 40px;
  }
}
</style>

<template>
  <div class="meeting-room-container" style='position:relative;border: 1px solid #e4e7ed;width:100%;overflow: auto;;'>
    <!-- 左侧会议室列表 -->
    <div class="room-list-sidebar" style="box-sizing: border-box;position:sticky;left: 0px;z-index: 887;;;">
      <div class="room-list-header" style="height: 46px;display: flex;align-items: center;justify-content: center;;">
        <h3 style="padding:0px;">会议室</h3>
      </div>
      <div class="room-list">
        <div v-for="(room, index) in liveroomList" :key="index" class="room-item"
           @click="selectRoom(index)">
          <div class="room-name">{{ room.name }}</div>
          <div class="room-info">{{ room.capacity || '6' }}人 · {{ room.equipment || '电视/白板' }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧时间表格区域 -->
    <div class="schedule-area" :style="`width:${60 * 24}px`">
      <!-- 时间标题行 -->
      <div class="time-header" :style="`width:${60 * 24}px`">
        <div class="time-cell" v-for="hour in 24" :key="hour">
          {{ String(hour - 1).padStart(2, '0') }}:00
        </div>
      </div>

      <!-- 时间表格 -->
      <div class="time-table" ref="timeTable" @mousemove="handleMouseMove" @mouseleave="hideMouseLine"
        :style="`width:${60 * 24}px`">
        <!-- 鼠标跟随蓝线 -->
        <div class="mouse-line" ref="mouseLine"
          :style="{ left: mouseLinePosition + 'px', display: showMouseLine ? 'block' : 'none' }"></div>

        <!-- 会议室行 -->
        <div v-for="(room, roomIndex) in liveroomList" :key="roomIndex" class="room-row">
          <!-- 时间格子 -->
          <div v-for="slot in 48" :key="slot" class="time-slot" :data-room="roomIndex" :data-slot="slot - 1"
            @mousedown="startSelection($event, roomIndex, slot - 1)"
            @mouseup="endSelection($event, roomIndex, slot - 1)"
            @mouseenter="updateSelection($event, roomIndex, slot - 1)">
            <!-- 已有预约事件渲染 -->
            <div v-for="(event, eventIndex) in getEventsForSlot(room, slot - 1)" :key="eventIndex" class="event-block"
              :style="getEventStyle(event)">
              <div class="event-block-innner" style="background-color:#409EFF;width: 100%;border-radius: 5px;;">
                <el-tooltip>
                  <div slot="content">会议已被 <span style="color:#409EFF;">{{ event?.title }}</span>预定 </div>
                  <div style="width: 100%;height: 60px;;">&nbsp</div>
                </el-tooltip>
              </div>

            </div>

            <!-- 过去时间的半透明遮罩 -->
            <div v-if="isPastTimeSlot(slot - 1)" class="past-time-overlay"></div>
          </div>
        </div>

        <!--  && selectionEnd -->
        <!-- 选择区域高亮 -->
        <div v-if="selectionStart && selectionEnd" class="selection-highlight" ref="selectionhighlightref"
          :style="getSelectionStyle()"></div>

        <!-- 预约确认Popover -->
        <div ref="bookingPopover" v-show="showBookingPopover" class="booking-popover"
          style="width:345px;;z-index: 1000; background: white; border: 1px solid #ddd; border-radius: 4px; padding: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.1);">
          <h4 style="padding:0px;margin:0px;">确认预约</h4>
          <p>会议室: {{ selectedRoomName }}</p>
          <p>时间: {{ formatTime(selectionStartTime) }} - {{ formatTime(selectionEndTime) }}</p>
          <div class="booking-actions">
            <el-button size="small" @click="cancelBooking">取消</el-button>
            <el-button type="primary" size="small" @click="confirmBooking">确认预约</el-button>
          </div>
        </div>

      </div>
    </div>


  </div>
</template>

<script>
import { createPopper } from '@popperjs/core';

export default {
  name: 'MeetingRoom',
  data() {
    return {
      // 时间格子固定尺寸常量
      SLOT_WIDTH: 30,  // 时间格子固定宽度(px)
      SLOT_HEIGHT: 45, // 时间格子固定高度(px)

      testStyleObj: {
        'left': '4.166666666666667%',
        'width': '4.166666666666667%',
        'top': '240px', 'height': '60px'
      },
      // 会议室数据
      liveroomList: [
        {
          name: 'NO.6会议室 (5楼)',
          capacity: '6人',
          equipment: '电视/白板',
          eventList: [
            {
              startTime: '09:00',
              endTime: '10:30',
              title: '项目讨论会',
              userName: 'lmt'
            },
            {
              startTime: '14:00',
              endTime: '15:30',
              title: '客户会议',
              userName: 'lmt2'
            }
          ]
        },
        {
          name: 'NO.5会议室 (5楼)',
          capacity: '8人',
          equipment: '投影/白板',
          eventList: [
            {
              startTime: '10:00',
              endTime: '12:00',
              title: '团队会议'
            }
          ]
        },
        {
          name: '大会议室 (5楼)',
          capacity: '50人',
          equipment: '电视/投影/音响/话筒',
          eventList: []
        },
        {
          name: '19F会议室',
          capacity: '10人',
          equipment: '电视',
          eventList: [
            {
              startTime: '16:00',
              endTime: '18:00',
              title: '部门例会'
            }
          ]
        },
        {
          name: 'NO.7会议室 (5楼)',
          capacity: '6人',
          equipment: '白板',
          eventList: [
            {
              startTime: '13:30',
              endTime: '15:00',
              title: '技术评审'
            }
          ]
        },
        {
          name: '白蓝咖啡影像 (3楼...)',
          capacity: '4人',
          equipment: '咖啡/休闲',
          eventList: []
        }
      ],

      // 界面状态
      selectedRoom: 0,
      showMouseLine: false,
      mouseLinePosition: 0,

      // 选择状态
      isSelecting: false,
      selectionStart: null,
      selectionEnd: null,
      selectionStartTime: '',
      selectionEndTime: '',

      // Popover状态
      showBookingPopover: false,
      popoverPosition: { x: 0, y: 0 }
    }
  },

  computed: {
    /**
     * 获取当前选中的会议室名称
     */
    selectedRoomName() {
      return this.liveroomList[this.selectedRoom]?.name || '';
    },

    /**
     * 获取当前时间对应的时间槽索引
     */
    currentTimeSlot() {
      const now = new Date();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      return hours * 2 + Math.floor(minutes / 30);
    }
  },

  methods: {
    /**
     * 选择会议室
     */
    selectRoom(index) {
      this.selectedRoom = index;
    },

    /**
     * 判断时间槽是否为过去时间
     */
    isPastTimeSlot(slotIndex) {
      return slotIndex < this.currentTimeSlot;
    },

    /**
     * 处理鼠标移动事件，显示跟随蓝线
     */
    handleMouseMove(event) {
      if (!this.$refs.timeTable) return;

      const rect = this.$refs.timeTable.getBoundingClientRect();
      const x = event.clientX - rect.left;

      // 计算对应的时间刻度位置
      const slotWidth = rect.width / 48;
      const slotIndex = Math.floor(x / slotWidth);
      const snapPosition = slotIndex * slotWidth + slotWidth / 2;

      this.mouseLinePosition = snapPosition;
      this.showMouseLine = true;
    },

    /**
     * 隐藏鼠标跟随线
     */
    hideMouseLine() {
      this.showMouseLine = false;
    },

    /**
     * 开始选择时间段
     * 检查当前时间槽是否已有会议活动或为过去时间，如果是则不允许选择
     */
    startSelection(event, roomIndex, slotIndex) {
      // 检查是否为过去时间
      if (this.isPastTimeSlot(slotIndex)) {
        this.isSelecting = false;
        this.selectionStart = undefined;
        this.selectionEnd = undefined;
        this.$message.warning('过去时间已经不可预约');
        event.preventDefault();
        return;
      }

      // 检查当前时间槽是否已有会议活动
      const room = this.liveroomList[roomIndex];
      const existingEvents = this.getEventsForSlot(room, slotIndex);

      if (existingEvents.length > 0) {
        // 如果当前位置已有会议活动，不允许开始选择
        this.isSelecting = false;
        this.selectionStart = undefined;
        this.selectionEnd = undefined;
        // this.$message.warning('该时间段已有会议安排，无法预约');
        console.log('该时间段已有会议安排，无法预约')
        event.preventDefault();
        return;
      }

      this.isSelecting = true;
      this.selectionStart = { room: roomIndex, slot: slotIndex };
      this.selectionEnd = { room: roomIndex, slot: slotIndex };
      this.selectedRoom = roomIndex;

      // 阻止默认行为
      event.preventDefault();
    },

    /**
     * 更新选择范围
     */
    updateSelection(event, roomIndex, slotIndex) {
      if (this.isSelecting && this.selectionStart) {
        this.selectionEnd = { room: roomIndex, slot: slotIndex };
      }
    },

    /**
     * 结束选择时间段
     */
    endSelection(event, roomIndex, slotIndex) {
      if (!this.isSelecting) return;

      // 检查是否为过去时间
      if (this.isPastTimeSlot(slotIndex)) {
        this.isSelecting = false;
        this.selectionStart = undefined;
        this.selectionEnd = undefined;
        this.$message.warning('过去时间已经不可预约');
        event.preventDefault();
        return;
      }

      // 检查当前时间槽是否已有会议活动
      const room = this.liveroomList[roomIndex];
      const existingEvents = this.getEventsForSlot(room, slotIndex);

      if (existingEvents.length > 0) {
        // 如果当前位置已有会议活动，不允许开始选择
        this.isSelecting = false;
        this.selectionStart = undefined;
        this.selectionEnd = undefined;
        // this.$message.warning('该时间段已有会议安排，无法预约');
        console.log('结束的时候校验：该时间段已有会议安排，无法预约')
        event.preventDefault();
        return;
      }


      this.isSelecting = false

      this.selectionEnd = { room: roomIndex, slot: slotIndex };

      // 计算选择的时间范围
      const startSlot = Math.min(this.selectionStart.slot, this.selectionEnd.slot);
      const endSlot = Math.max(this.selectionStart.slot, this.selectionEnd.slot) + 1;

      this.selectionStartTime = this.slotToTime(startSlot);
      this.selectionEndTime = this.slotToTime(endSlot);

      // 显示确认Popover
      this.showBookingPopover = true;

      // 使用Popper.js定位弹窗
      this.$nextTick(() => {
        const button = this.$refs.selectionhighlightref;
        const tooltip = this.$refs.bookingPopover;

        if (button && tooltip) {
          // 销毁之前的popper实例
          if (this.popperInstance) {
            this.popperInstance.destroy();
          }

          // 创建新的popper实例
          this.popperInstance = createPopper(button, tooltip, {
            modifiers: [
              {
                name: 'offset',
                options: {
                  offset: [0, 8],
                },
              },
              {
                name: 'preventOverflow',
                options: {
                  boundary: 'viewport',
                },
              },
              {
                name: 'computeStyles',
                options: {
                  adaptive: true, // true by default
                },

              }
            ],
          });
        }
      });
    },

    /**
     * 取消预约
     */
    cancelBooking() {
      this.showBookingPopover = false;
      this.clearSelection();
      this.isSelecting = false;

      // 销毁popper实例
      if (this.popperInstance) {
        this.popperInstance.destroy();
        this.popperInstance = null;
      }
    },

    /**
     * 确认预约
     */
    confirmBooking() {
      // 创建新的会议事件对象
      const newEvent = {
        id: Date.now(), // 使用时间戳作为唯一ID
        title: '新预约会议',
        startTime: this.selectionStartTime,
        endTime: this.selectionEndTime,
        duration: this.timeToSlot(this.selectionEndTime) - this.timeToSlot(this.selectionStartTime)
      };
      console.log('确定之后推送的event', this.selectedRoom, newEvent)

      // 将新事件添加到对应会议室的eventList中
      if (this.liveroomList[this.selectedRoom]) {
        this.liveroomList[this.selectedRoom].eventList.push(newEvent);
      }

      this.$message.success(`预约成功: ${this.selectedRoomName} ${this.selectionStartTime}-${this.selectionEndTime}`);
      this.showBookingPopover = false;
      this.clearSelection();
      debugger

      // 销毁popper实例
      if (this.popperInstance) {
        this.popperInstance.destroy();
        this.popperInstance = null;
      }
    },

    /**
     * 获取选择区域的样式
     */
    getSelectionStyle() {
      if (!this.selectionStart || !this.selectionEnd) return {};

      const startSlot = Math.min(this.selectionStart.slot, this.selectionEnd.slot);
      const endSlot = Math.max(this.selectionStart.slot, this.selectionEnd.slot);
      const roomIndex = this.selectionStart.room;

      // const slotWidth = 100 / 48; // 百分比宽度
      const slotWidth = this.SLOT_WIDTH; // 百分比宽度
      const roomHeight = 65; // 每行高度

      // console.log('startSlot',startSlot)
      // console.log('select width', `${(endSlot - startSlot + 1) * slotWidth}%`)

      return {
        left: `${startSlot * slotWidth}px`,
        width: `${(endSlot - startSlot + 1) * slotWidth}px`,
        top: `${roomIndex * roomHeight}px`,
        height: `${roomHeight}px`
      };
    },

    /**
     * 将时间槽索引转换为时间字符串
     */
    slotToTime(slotIndex) {
      const hours = Math.floor(slotIndex / 2);
      const minutes = (slotIndex % 2) * 30;
      return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
    },

    /**
     * 格式化时间显示
     */
    formatTime(timeStr) {
      return timeStr;
    },

    /**
     * 获取指定时间槽的事件
     * 只在事件的起始时间槽显示事件，避免重复渲染
     */
    getEventsForSlot(room, slotIndex) {
      if (!room.eventList) return [];

      return room.eventList.filter(event => {
        const eventStart = this.timeToSlot(event.startTime);
        // 只在事件开始的时间槽显示事件
        return slotIndex === eventStart;
      });
    },

    /**
     * 将时间字符串转换为时间槽索引
     */
    timeToSlot(timeStr) {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 2 + Math.floor(minutes / 30);
    },

    /**
     * 获取事件块的样式
     * 计算事件的完整时间跨度宽度
     */
    getEventStyle(event) {
      const startSlot = this.timeToSlot(event.startTime);
      const endSlot = this.timeToSlot(event.endTime);
      const duration = endSlot - startSlot;

      return {
        // 使用固定的SLOT_WIDTH计算事件宽度
        width: `${duration * this.SLOT_WIDTH}px`,
        left: '0',
        color: 'white',
        padding: '2px 4px',
        borderRadius: '2px',
        fontSize: '12px',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        textOverflow: 'ellipsis',
        position: 'absolute',
        height: '100%'
      };
    },

    // /**
    //  * 确认预约
    //  */
    // confirmBooking() {
    //   // 这里可以添加预约逻辑
    //   this.$message.success(`预约成功: ${this.selectedRoomName} ${this.selectionStartTime}-${this.selectionEndTime}`);
    //   this.showBookingPopover = false;
    //   this.clearSelection();
    // },

    /**
     * 取消预约
     */
    cancelBooking() {
      this.showBookingPopover = false;
      this.clearSelection();
    },

    /**
     * 清除选择状态
     */
    clearSelection() {
      this.selectionStart = null;
      this.selectionEnd = null;
      this.isSelecting = false;
    }
  },

  beforeDestroy() {
    // 组件销毁时清理popper实例
    if (this.popperInstance) {
      this.popperInstance.destroy();
    }
  }
}
</script>
